<template>
  <div class="edit-header">
    <p>广告活动</p>
  </div>
  <a-form ref="formRef" :disabled="isDisabled" style="max-width: 900px" :model="editSpCampaignInfo" :rules="rules">
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item field="shopId" label="店铺" label-col-flex="100px">
          <a-select v-model="editSpCampaignInfo.shopId" placeholder="请选择" allow-search @change="changeShop">
            <a-option v-for="(shop, i) in shopList" :key="i" :value="shop.id" :label="shop.shopName" />
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item field="campaignName" label="广告活动名称" label-col-flex="100px">
          <a-input v-model="editSpCampaignInfo.campaignName" placeholder="请输入" allow-clear />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item field="portfolioInfo.portfolioId" label="广告组合" label-col-flex="100px">
          <a-select v-model="editSpCampaignInfo.portfolioInfo" value-key="portfolioId" placeholder="请选择" allow-search @search="getPortfoliosListByShopId">
            <a-option v-for="(portfolio, i) in portfoliosList" :key="i" :value="portfolio" :label="portfolio.portfolioName" />
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item field="startDate" label="广告活动时间" label-col-flex="100px">
          <a-date-picker style="margin-right: 5px" v-model="editSpCampaignInfo.startDate" placeholder="开始日期(必填)" />
          <a-date-picker v-model="editSpCampaignInfo.endDate" placeholder="结束日期(选填)" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item field="budget" label="每日预算" label-col-flex="100px">
          <a-input-number v-model="editSpCampaignInfo.budget" placeholder="" allow-clear>
            <template #prepend>
              <a-button>{{ currency }}</a-button>
            </template>
          </a-input-number>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item field="targeting" label="投放类型" label-col-flex="100px">
          <a-radio-group v-model="editSpCampaignInfo.targeting" @change="updateSpCampaignInfo">
            <a-radio value="AUTO">
              <span>自动投放</span>
              <a-popover content="马逊将定向到关键词和与您广告中的商品类似的商品。">
                <icon-question-circle style="margin-left: 2px" />
              </a-popover>
            </a-radio>
            <a-radio value="MANUAL">
              <span>手动投放</span>
              <a-popover content="择可定向到顾客搜索的关键词或商品并设置自定义竞价。">
                <icon-question-circle style="margin-left: 2px" />
              </a-popover>
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>
<script lang="ts" setup>
  import { onMounted, ref, computed } from 'vue'
  import { getAllPortfoliosList } from '@/api/advert'
  import { findShopMarketByParam } from '@/api/system'
  import { marketPlaceList } from '@/utils/globalData'
  import { DraftFinishStep } from '../../types'
  const props = defineProps({
    darftInfo: {
      type: Object,
      default: () => {},
    },
    shop: {
      type: Object,
      default: () => {},
    },
  })
  const emit = defineEmits(['change'])
  onMounted(async () => {
    // 有草稿箱
    if (props.darftInfo?.draftId) {
      editSpCampaignInfo.value = JSON.parse(JSON.stringify(props.darftInfo))
      if (props.darftInfo.portfolioId) {
        editSpCampaignInfo.value.portfolioInfo = {
          portfolioId: props.darftInfo.portfolioId,
          portfolioName: props.darftInfo.portfolioName,
        }
      }
    } else {
      editSpCampaignInfo.value.targeting = 'AUTO'
      editSpCampaignInfo.value.shopId = props.shop?.shopId
    }
    getShopList()
    updateSpCampaignInfo()
  })
  const rules = ref({
    shopId: [{ required: true, message: '请选择店铺' }],
    campaignName: [{ required: true, message: '请输入广告活动名称' }],
    'portfolioInfo.portfolioId': [{ required: true, message: '请选择广告组合' }],
    startDate: [{ required: true, message: '请选择开始日期' }],
    budget: [{ required: true, message: '请输入每日预算' }],
    targeting: [{ required: true, message: '请选择投放类型' }],
  })

  const editSpCampaignInfo = ref<any>({})
  const shopList = ref<Array<any>>([])
  const portfoliosList = ref<Array<any>>([])
  const formRef = ref()
  // 根据当前流程节点判断是否可编辑
  let isDisabled = computed(() => {
    let handlerFlow = props.darftInfo?.handlerFlow || 'INIT'
    let level = DraftFinishStep[handlerFlow]
    return Number(level) > 0 ? true : false
  })
  // 币种
  const currency = ref('USD')

  // 切换店铺
  function changeShop() {
    let shop = shopList.value.find((el) => el.id == editSpCampaignInfo.value.shopId)
    editSpCampaignInfo.value.shop = shop
    currency.value = shop ? marketPlaceList[shop.marketplaceId]?.currency : 'USD'
    emit('change', 'shop', shop)
    getPortfoliosListByShopId()
  }
  // 获取店铺
  async function getShopList() {
    const res: any = await findShopMarketByParam()
    shopList.value = res?.data || []
    editSpCampaignInfo.value.shopId = editSpCampaignInfo.value.shopId || shopList.value[0]?.id
    changeShop()
  }
  // 获取组合列表数据
  async function getPortfoliosListByShopId(value?: any) {
    const res: any = await getAllPortfoliosList({
      search: value,
      shopId: editSpCampaignInfo.value.shopId,
    })
    portfoliosList.value = res?.data || []
  }
  // 校验信息
  async function validateData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    return valid ? false : true
  }
  // 设置需要创建的数据
  function setCreateData() {
    return {
      shopId: editSpCampaignInfo.value.shopId,
      campaignName: editSpCampaignInfo.value.campaignName,
      portfolioId: editSpCampaignInfo.value.portfolioInfo?.portfolioId,
      portfolioName: editSpCampaignInfo.value.portfolioInfo?.portfolioName,
      startDate: editSpCampaignInfo.value.startDate,
      endDate: editSpCampaignInfo.value.endDate,
      budget: editSpCampaignInfo.value.budget,
      targeting: editSpCampaignInfo.value.targeting,
    }
  }
  // 需要实时保存的数据
  function updateSpCampaignInfo() {
    emit('change', 'targeting', editSpCampaignInfo.value.targeting)
  }
  defineExpose({ validateData, setCreateData })
</script>
<style lang="less" scoped>
  .edit-header {
    background-color: var(--color-fill-2) !important;
    border-left: 2px solid rgb(var(--primary-6));
    line-height: 32px;
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 20px;
  }
  :deep(.arco-input-prepend) {
    padding: 0;
  }
</style>
